<template>
  <div id="cart">
    <!--头部区域-->
<!--    <header style="margin-top: 10px; position: fixed;">-->
<!--        <van-row type="flex" justify="space-around">-->
<!--            <van-col offset="1" span="8"> <button style="background-color: transparent;font-size: 14px">< 返回</button></van-col>-->
<!--            <van-col span="6"> <h4><strong>购物车</strong></h4></van-col>-->
<!--            <van-col span="6"> <button style="font-size: 12px;background-color: transparent;color:red" @click="clearCart">清空购物车</button></van-col>-->
<!--        </van-row>-->
<!--    </header>-->
<!--      left-text="返回"-->
<!--      @click-left="onClickLeft"-->
      <van-nav-bar
              title="购物车"
              right-text="清空购物车"
              @click-right="onClickRight"
      />
    <div class="contentWrapper">
<!--      中间内容-->
      <main class="contentWrapperList" v-show="cartContent">
                 <template v-for="(goods,index) in shopCart">
<!--          <div class="shopCartListCon" v-for="(goods,index) in shopCart" :key="goods.id">-->
                  <!-- eslint-disable-next-line vue/no-unused-vars -->
                      <van-swipe-cell :before-close="beforeClose">
                          <section>
                              <div class="shopCartListCon"  :key="goods.id">
                              <div class="left">
                                  <a @click.stop="singerGoodsSelected(goods.id)" href="javascript:" class="cartCheckBox"
                                     :checked="goods.check !== '0'"></a>
                              </div>
                              <div class="center">
                                  <img :src=baseURL1+goods.img alt="">
                              </div>
                              <div class="right">
                                  <a href="#">{{ goods.name }}</a>
                                  <p>{{goods.colorName +" "+goods.sizeName}}</p>
                                  <div class="bottomContent">
                                      <p class="shopPrice">{{ goods.price|moneyFormat }}</p>
                                      <div class="shopDeal">
                                          <span @click="removeOutCart(goods.id,goods.count)" class="co-lor">-</span>
                                          <!-- eslint-disable-next-line vue/valid-v-model -->
                                          <input type="number" v-model="goods.count">
                                          <span @click="addToCart(goods.id)" class="co-lor">+</span>
                                      </div>
                                  </div>
                              </div>
                              </div>
                          </section>
                          <template #right>
                                  <van-button square text="删除" type="danger" class="delete-button" @click="clickGoodsId(goods.id)"/>
                          </template>
                      </van-swipe-cell>
<!--            </div>-->
                 </template>

      </main>
        <van-empty v-show="empty"
                class="custom-image"
                image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
                description="暂无商品"
        />

        <!--底部通栏-->
      <div class="tabBar">
        <div class="tabBarLeft">
          <a
              @click="changeChecked"
              @click.stop="selectedAll(isSelectedAll)"
              :checked="isSelectedAll"
              href="javascript:"
              class="cartCheckBox"
          ></a>
          <span style="font-size: 16px;">全选</span>
          <div class="selectAll">
            合计：<span class="totalPrice">{{ totalPrice|moneyFormat }}</span>
          </div>
        </div>
        <div class="tabBarRight">
          <button @click="toPay" class="pay">去结算({{ goodsCount }})
          </button>
        </div>
      </div>
    </div>
  </div>
  <!--<SelectLogin v-else/>-->
</template >


<script>

import {cartGoodsList,clearShopCart,deleteCartGoods,exitGoodsCount} from "@/api/api";
import {mapMutations} from 'vuex'
import {Dialog, Toast} from "vant";
import img from "@/api/api"
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Cart",
  created() {
    cartGoodsList().then((response) => {
      this.shopCart = response.data.data.cartInfo;
            if(this.shopCart!==undefined && this.shopCart.length>0){
          this.empty=false;
          this.cartContent=true;
      }else{
          this.empty=true;
          this.cartContent=false;

      }
      console.log( this.shopCart )
    });
  },
  data() {
    return{
        cartContent:false,
        empty:false,
        goodsId:"",
      shopCart: [],
      baseURL1:img.src,
      isSelectedAll:false,
      toSendId:0,
      toSendCount:0
    }
  },
  computed: {
    // ...mapState(["shopCart", "userInfo"]),
    // 0. 商品总件数
    goodsCount() {
      let goodsCount = 0;
      if(this.shopCart!==undefined && this.shopCart.length>0){
        Object.values(this.shopCart).forEach((goods, index) => {
          if(goods.check !== '0'){
            goodsCount+=parseInt(goods.count);
          }
        })
      }
      return goodsCount;
    },

    // 2. 计算商品总价
    totalPrice() {
      let totalPrice = 0;
      if(this.shopCart!==undefined && this.shopCart.length>0){
        Object.values(this.shopCart).forEach((goods, index) => {
          if(goods.check !== '0'){
            totalPrice += goods.count * goods.price;
          }
        })
      }
      return totalPrice;
    },

  },
  methods: {
    ...mapMutations(["saveShopCart"]),
    // 1. 商品是否全选
    changeChecked() {
      this.isSelectedAll = !this.isSelectedAll
    },
      beforeClose({ position, instance }) {
          switch (position) {
              case 'left':
              case 'cell':
              case 'outside':
                  instance.close();
                  break;
              case 'right':
                  Dialog.confirm({
                      message: '确定删除吗？',
                  }).then(() => {
                          deleteCartGoods(this.goodsId).then(
                              (resp)=>{
                                  if(resp.data.code === 2000){
                                      location.reload()
                                  }else{
                                      Toast(resp.data.message);
                                  }
                              })
                  }).catch(()=>{
                      instance.close();
                  });
                  break;
          }
      },
    // 1. 移出购物车
    async removeOutCart(goodsId, goodsNum) {
      // if (goodsNum > 1) {
      //   let result = await changeCartNum(this.userInfo.token, goodsId, 'reduce');
      //   // console.log(result)
      //   if (result.success_code === 200) {
      //     this.REDUCE_CART({goodsId});
      //   } else {
      //     Toast({
      //       message: "出了点小问题哟",
      //       duration: 600
      //     })
      //   }
      // } else if (goodsNum === 1) {
      //   // 弹窗挽留
      //   Dialog.confirm({
      //     title: '温馨提示',
      //     message: '确定删除该商品吗？',
      //   }).then(async () => {// 确定
      //     let result = await changeCartNum(this.userInfo.token, goodsId, 'reduce');
      //     // console.log(result)
      //     if (result.success_code === 200) {
      //       this.REDUCE_CART({goodsId});
      //     } else {
      //       Toast({
      //         message: "出了点小问题哟",
      //         duration: 600
      //       })
      //     }
      //   }).catch(() => {// 取消
      //     // do nothing
      //   });
      // }
      this.toSendId = goodsId;
      if(goodsNum > 1){
        Object.values(this.shopCart).forEach((goods, index) => {
          if(goods.id === goodsId){
            goods.count--;
            this.toSendCount = goods.count;
          }
        })
      }else{
        Dialog.confirm({
          title: '温馨提示',
          message: '确定删除该商品吗？'
        }).then(()=>{
          deleteCartGoods(goodsId).then(
              (resp)=>{
                if(resp.data.code === 2000){
                  location.reload()

                }else{
                  Toast(resp.data.message);
                }
              })
        }).catch(()=>{

        });
      }
    },
    // 2. 增加商品
    async addToCart(goodsId) {
      // let result = await changeCartNum(this.userInfo.token, goodsId, 'add');
      // // console.log(result)
      // if (result.success_code === 200) {
      //   this.ADD_GOODS({goodsId, goodsName, smallImage, goodsPrice})
      // } else {
      //   Toast({
      //     message: "出了点小问题哟",
      //     duration: 600
      //   })
      // }
      this.toSendId = goodsId;
        Object.values(this.shopCart).forEach((goods, index) => {
          if(goods.id === goodsId){
            goods.count++;
            this.toSendCount = goods.count;
          }
        })
    },
    // 3. 单个商品选中和取消选中
    async singerGoodsSelected(goodsId) {
      // let result = await singerGoodsSelect(this.userInfo.token, goodsId);
      // if (result.success_code === 200) {
      //   this.SELECTED_SINGLE_GOODS({goodsId});
      // } else {
      //   Toast({
      //     message: "出了点错误",
      //     duration: 500
      //   })
      // }
      for(let i = 0; i < this.shopCart.length;i++){
        if(this.shopCart[i].id == goodsId){
          if(this.shopCart[i].check === '0'){
            this.shopCart[i].check = '1';
          }else{
            this.shopCart[i].check = '0';
          }
          break;
        }
      }
    },
    // 4. 全选和取消全选
    async selectedAll(isSelectedAll) {
      // let result = await allGoodsSelect(this.userInfo.token, isSelected);
      // if (result.success_code === 200) {
      //   this.SELECTED_ALL_GOODS({isSelected});
      // } else {
      //   Toast({
      //     message: "出了点错误",
      //     duration: 500
      //   })
      // }
      for(let i = 0; i < this.shopCart.length;i++){
        if(isSelectedAll === true){
            this.shopCart[i].check = '1';
          }else{
            this.shopCart[i].check = '0';
          }
      }
    },
      // onClickLeft() {
      //     this.$router.go(-1)
      // },
    // 5. 清空购物车
      onClickRight() {
      // Dialog.confirm({
      //   title: '温馨提示',
      //   message: '确定清空所有商品吗？'
      // }).then(async () => {
      //   let result = await clearAllCart(this.userInfo.token);
      //   if (result.success_code === 200) {
      //     this.CLEAR_CART();
      //   } else {
      //     Toast({
      //       message: "出了点小问题哟",
      //       duration: 500
      //     })
      //   }
      // }).catch(() => {
      // });
      if(this.shopCart.length>0){
        let gtd = [];
        Object.values(this.shopCart).forEach((goods, index) => {
          gtd.push(goods.id);
        })
        Dialog.confirm({
          title: '清空提示',
          message: '确定清空所有商品吗？'
        }).then(()=>{
          clearShopCart(gtd).then((resp)=>{
            if(resp.data.code === 2000){
              location.reload()
            }else {
              Toast(resp.data.message);
            }
          })
        });
      }else{
        Dialog.alert({
          title: '温馨提示',
          message: '没有商品可清空哦(*^_^*)'
        })
      }

    },
      clickGoodsId(id){
        this.goodsId=id;
      },
    // 6. 去支付
    toPay() {
      let result = [];
      Object.values(this.shopCart).forEach((goods, index) => {
        if(goods.check !== '0'){
          result.push(goods);
        }
      })
      if(result.length === 0){
        Dialog.alert({
          title: '购买提示',
          message: '没有商品可结算哦(*^_^*)'
        });
        return;
      }
      this.saveShopCart(result);
      if(this.toSendId>0&&this.toSendCount>0){
        exitGoodsCount(this.toSendId,this.toSendCount).then(
            (resp)=>{
              if(resp.data.code === 2000){
                this.toSendId = 0;
                this.toSendCount = 0;
                location.reload();
              }else {
                Toast(resp.data.message);
              }
            }
        );
      }
        this.$router.push(
            {path:'/confirmOrder',
                query:{
                    cart:this.shopCart,
                    cartNow:1
                }
            })
    }
  },
  // components: {
  //   SelectLogin
  // }

  destroyed: function () {
    if(this.toSendId>0&&this.toSendCount>0){
      exitGoodsCount(this.toSendId,this.toSendCount).then(
          (resp)=>{
            if(resp.data.code === 2000){
              this.toSendId = 0;
              this.toSendCount = 0;
              location.reload();
            }else {
              Toast(resp.data.message);
            }
          }
      );
    }
  },

}
</script>

<style lang="less" scoped>
#cart {
  width: 100%;
  height: 100%;
  background-color:white;
}

.titleWrapper {
  width: 100%;
  height: 2.6rem;
  background: #fff;
  -webkit-background-size: 0.1rem 4.4rem;
  background-size: 0.1rem 4.4rem;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;

  display: flex;
  justify-content: center;
  align-items: center;
}

.titleWrapper .clearCart {
  background-color: transparent;
  position: absolute;
  right: 0.6rem;
  color: red;
  font-size: 0.8rem;
}
.delete-button {
  height: 100%;
}
.contentWrapper {
  padding-top: 0.5rem;
}

/*列表内容*/
.contentWrapperList {
  padding-bottom: 6rem;
}

.contentWrapperList section {
  background-color: #fff;
}

.cartCheckBox {
  background: url("./images/shop-icon.png") no-repeat;
  -webkit-background-size: 2.5rem 5rem;
  background-size: 2.5rem 5rem;
  width: 1rem;
  height: 1rem;
}

.cartCheckBox[checked] {
  background-position: -1.2rem 0;
}

.shopCartListCon {
  display: flex;
  height: 6rem;
  border-bottom: 0.01rem solid #e0e0e0;
  margin-bottom: 0.7rem;
  padding: 0.5rem 0;
}

.shopCartListCon .left {
  /*background: purple;*/
  flex: 1;
  display: flex;
  /*justify-content: center;*/
}

.shopCartListCon .left a {
  display: inline-block;
  margin-top: 0.8rem;
  margin-left: 0.5rem;
}

.shopCartListCon .center {
  /*background: blue;*/
  flex: 3;
}

.shopCartListCon .center img {
  width: 100%;
  height: 100%;
}

.shopCartListCon .right {
  /*background: orangered;*/
  flex: 6;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-left: 0.5rem;
  margin-right: 0.5rem;

  position: relative;
}

.shopCartListCon .right a {
  height: 2.2rem;
  line-height: 1.2rem;
  overflow: hidden;
  margin-bottom: 0.3rem;
  font-size: 0.8rem;
  color: #000;
}

.shopCartListCon .bottomContent {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.shopCartListCon .bottomContent .shopPrice {
  font-size: 0.8rem;
}

.shopCartListCon .right .shopDeal span {
  display: inline-block;
  width: 1rem;
  height: 1.2rem;
  line-height: 1.2rem;
  text-align: center;
  float: left;
}

.shopCartListCon .right .shopDeal input {
  float: left;
  width: 2rem;
  height: 1.2rem;
  text-align: center;
  margin: 0 0.2rem;
  font-size: 0.8rem;
}

/*底部通栏*/
.tabBar {
  position: fixed;
  left: 0;
  bottom: 2.7rem;
  width: 100%;
  height: 2.5rem;
  background-color: #fff;

  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 0.01rem solid #e0e0e0;
}

.tabBarLeft {
  display: flex;
  align-items: center;
  margin-left: 0.5rem;
}

.tabBarLeft .selectAll {
  margin-left: 1rem;
  font-size: 1rem;
}

.totalPrice {
  color: #E9232C;
}

.tabBarRight .pay {
  width: 5rem;
  height: 2rem;
  background-color: #E9232C;
  border-radius: 1rem;
  margin-right: 0.5rem;

  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  color: #fff;
}
.co-lor{
  background-color: orangered;
  color: snow;
}
</style>

